import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;

import java.util.List;

/****
 *  MagicMaker  55AA  2 byte
 *  PackLen  1 Word   2 byte
 *  CommandId 1 Integer
 *  SID 1 integer  4 byte
 *  ServerID 1 integer
 *  ClientId 1 integer
 *
 */

public class MyProtoDecoder extends ByteToMessageDecoder {

    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
        if (in.readableBytes() < 20) {
            return;
        }

        in.markReaderIndex();

        int marker = in.readUnsignedShort();
        if (marker != 0x55AA) {
            in.clear();
            System.err.println("Package Decoder Failure!!!");
            ctx.close();
            return;
        }

        int packlen = in.readShort();
        int cmd = in.readInt();
        int sid = in.readInt();
        int serid = in.readInt();
        int cliid = in.readInt();

        if (in.readableBytes() < (packlen - 20)) {
            in.resetReaderIndex();
            return;
        }

        byte[] data = new byte[packlen - 20];
        in.readBytes(data);
        out.add(new MyProtoPackage(cmd, sid, serid,cliid, data));
    }
}